
<template>
  <a-modal :visible="visible" title="设置请求头" @ok="handleOk" @cancel="$emit('update:visible', false)" :footer="false"
    width="50%">
    <a-table rowKey="id" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :pagination="false" :columns="columns" :dataSource="dataSource" size="small">
      <template #name="{record}">
        <input class="input" v-model="record.name"/>
      </template>
      <template #value="{record}">
        <input class="input" autocomplete="false" v-model="record.value"/>
      </template>
      <template #operation="{ record }">
        <button @click="deleteLine(record)">删除</button>
      </template>
    </a-table>
    <a-button type="dashed" block dash @click="addLine">新增行</a-button>
  </a-modal>
</template>
<script setup lang="ts">
import { useLocalStorage } from '@vueuse/core';
import { uuid } from 'howtools';
import { computed, unref } from 'vue';
import { message } from 'ant-design-vue';
import { Key } from 'ant-design-vue/lib/vc-tree/interface';
const dataSource = useLocalStorage<{ name: string, value: string, id: string, checked: boolean }[]>("__headers", [])
const selectedRowKeys = computed(() => unref(dataSource).filter(item => item.checked).map(item=>item.id))

const props = defineProps({
  visible: {
    default: false,
    type: Boolean,
  },
  getway: {
    default: "",
    type: String,
  },
})
const columns = [
  {
    dataIndex: "name",
    title: "名称",
    slots: { customRender: 'name' },
    width: 160
  },
  {
    dataIndex: "value",
    title: "值",
    slots: { customRender: 'value' },
  },
  {
    dataIndex: "operation",
    title: "操作",
    slots: { customRender: 'operation' },
  },
]

function addLine() {
  if(unref(dataSource).length >= 20){
    message.error("最多设置20条数据")
    return
  }
  dataSource.value.push({
    id: uuid(),
    name: "",
    value: "",
    checked: false,
  })
}

function deleteLine({ id }: { id: string }) {
  const idx = unref(dataSource).findIndex(item => item.id === id)
  dataSource.value.splice(idx, 1)
}

const handleOk = (e: MouseEvent) => {
  e.preventDefault();
};

function onSelectChange(selectedRowKeys: Key[]) {
  console.log(selectedRowKeys);
  

  unref(dataSource).forEach(item => item.checked = false)
  for (const key of selectedRowKeys) {
    const f = unref(dataSource).find(item => item.id === key)
    if (f) {
      f.checked = true
    }
  }
}
</script>
<style scoped>
.input {
  width: 100%;
}
</style>